<?php

/**
 * 更新内容近7天得ctr数据
 * 大数据（数据生成时间在凌晨1:45之前）
 * 后端 每天凌晨2点5分开始更新数据
 */
ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Biz\model\brandData\ContentCtr;
use Doraemon\pockets\config\IniConfig;
use Doraemon\tools\Log;
use Doraemon\tools\Presto\PrestoClientV2;


$config = IniConfig::getConfigSelect('presto', 'brand');
$presto = new PrestoClientV2("{$config['host']}:{$config['port']}/{$config['path']}", "hive", $config["username"], $config["password"]);

var_dump('开始处理时间：' . date('Y-m-d H:i:s'));
$startTime = microtime(true);
$maxIdRes = [];
try {
    $presto->Query("select max(rank) from oss.hhz.ads_content_ctr");
    $presto->WaitQueryExec();
    $maxIdRes = $presto->GetData();
} catch (\Doraemon\tools\Presto\PrestoException $e) {
    Log::error('查询内容ctr数据失败' . $e);
}

if ($maxIdRes) {
    var_dump('重置数据开始:' . date('Y-m-d H:i:s'));
    ContentCtr::update(['ctr_status' => ContentCtr::CTR_STATUS_DELETE]);
    var_dump('重置数据结束:' . date('Y-m-d H:i:s'));

    $pageSize = 20000;
    $maxId = $maxIdRes[0][0];
    var_dump('开始更新，最大id:' . $maxId);
    $startId = 0;
    $endId = 0;
    try {
        while ($startId < $maxId) {
            $queryStartTime = microtime(true);
            try {
                $startId = $endId;
                $endId = $startId + $pageSize;
                $presto->Query("select * from oss.hhz.ads_content_ctr where rank>$startId and  rank<=$endId");
                $presto->WaitQueryExec();
            } catch (\Doraemon\tools\Presto\PrestoException $e) {
                Log::error('查询内容ctr数据失败' . $e);
            }
            $dataInfo = $presto->GetData();
            $queryEndTime = microtime(true);
            var_dump('查询第' . $startId . '至' . $endId . '条,耗时：' . round($queryEndTime - $queryStartTime, 3) . '秒');
            if ($dataInfo) {
                var_dump('>>>>>>更新ctr数据开始' . date('Y-m-d H:i:s'));
                foreach ($dataInfo as $data) {
                    $contentCtrData = [
                        'obj_id' => $data[1],
                        'click_cnt' => $data[2] ?? 0,
                        'exp_cnt' => $data[3] ?? 0,
                        'ctr' => $data[4] ?? 0,
                        'ctr_status' => ContentCtr::CTR_STATUS_NORMAL,
                        'update_time' => date('Y-m-d H:i:s')
                    ];
                    ContentCtr::addData($contentCtrData);
                }
                var_dump('>>>>>>更新ctr数据结束' . date('Y-m-d H:i:s'));
            }
        }
        $stopTime = microtime(true);
        $timeSpent = $stopTime - $startTime;
        $timeSecond = round($timeSpent, 3);
        var_dump('处理完成时间：' . date('Y-m-d H:i:s') . '   总耗时:' . $timeSecond . '秒');
    } catch (Exception $exception) {
        Log::info('查询内容ctr数据失败', ['exception' => $exception]);
    }

} else {
    var_dump('查询失败', $maxIdRes);
}